<template>
  <el-drawer
    :visible.sync="drawerVisible"
    title="导出客群画像结果"
    size="60%"
    direction="rtl"
    :close-on-press-escape="false"
    custom-class="tag-drawer factory-download-drawer"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    @closed="clearDrawer"
    v-drawerResize
  >
    <div class="drawer-wrap" v-loading="loading">
      <div class="drawer-content tag-scrollbar">
        <el-row>
          <el-col :span="12">
            <div class="list-wrapper">
              <div class="list-box">
                <tag-content-header>
                  <template #title>
                    <span>候选标签列表</span>
                  </template>
                </tag-content-header>
                <div class="filter">
                  <el-input
                    v-model="keyword"
                    clearable
                    placeholder="输入搜索关键字"
                    @clear="clearKeyword"
                    @keyup.native.enter="search"
                  >
                    <el-button slot="append" @click="search"><icon-svg name="iconSearch"></icon-svg></el-button>
                  </el-input>
                </div>
              </div>
              <div class="list-content unselect tag-scrollbar" v-loading.lock="loading">
                <div v-if="selected.length && selected[selected.length - 1].catalogId" class="tab-title">
                  <icon-svg name="iconReturn" @click.native="prev"></icon-svg>
                  <el-breadcrumb separator="/" ref="factoryBread">
                    <div class="elli" v-if="breadLeft < 0">...</div>
                    <el-breadcrumb-item
                      v-for="(item, index) in selected"
                      :key="index"
                      :class="{ normal: index === selected.length - 1 }"
                      :style="index === 0 ? { marginLeft: breadLeft + 'px' } : null"
                      @click.native="changeTab(index)"
                      >{{ item.catalogNm }}</el-breadcrumb-item
                    >
                  </el-breadcrumb>
                </div>
                <template v-if="showList.length && showList[0].tagId">
                  <ul class="list">
                    <li v-for="item in showList" :key="item.tagId" class="list-item">
                      <div class="asset-name">{{ item.tagNm }}</div>
                      <div class="list-handler">
                        <el-tooltip
                          effect="dark"
                          content="添加"
                          placement="top"
                          :enterable="false"
                          v-if="unselected(item)"
                        >
                          <el-button icon="el-icon-plus" size="mini" plain circle @click="addSelect(item)"></el-button>
                        </el-tooltip>
                        <span class="tip" v-else>已选择</span>
                      </div>
                    </li>
                  </ul>
                  <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="params.currentPageNum"
                    :page-size="params.pageSize"
                    :pager-count="5"
                    background
                    layout="total, prev, pager, next"
                    small
                    :total="totalSize"
                  >
                  </el-pagination>
                </template>
                <ul v-else-if="showList.length && showList[0].catalogId" class="list">
                  <li
                    v-for="item in showList"
                    :key="item.catalogId"
                    @click="handleClickCatalog(item)"
                    class="list-item"
                  >
                    {{ item.catalogNm }} （{{ item.dataAssetCount }}）
                    <i class="el-icon-arrow-right"></i>
                  </li>
                </ul>
                <p v-else>{{ loading ? '' : '暂无内容' }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="1" class="add-icon"><i class="el-icon-d-arrow-right"></i></el-col>
          <el-col :span="11">
            <div class="list-wrapper">
              <div class="list-box">
                <tag-content-header>
                  <template #title>
                    <span>已选标签列表</span>
                  </template>
                </tag-content-header>
              </div>
              <div class="list-content">
                <ul class="list tag-scrollbar">
                  <li v-for="item in selectedList" :key="item.tagId" class="list-item">
                    {{ item.tagNm }}
                    <div class="list-handler">
                      <el-button icon="el-icon-close" size="mini" plain circle @click="removeSelect(item)"></el-button>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="beforeClose()">取消</el-button>
      <el-popover placement="top" width="400" v-model="popShow">
        <el-form label-width="120px">
          <el-form-item label="保存文件格式">
            <el-select v-model="fileType" size="mini" placeholder="请选择保存文件格式">
              <el-option
                v-for="dict in $dictList('std_file_fmt')"
                :key="dict.key"
                :label="dict.value"
                :value="dict.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件字符集" v-if="fileType !== 2">
            <el-select v-model="fileCharset" size="mini" placeholder="请选择文件字符集">
              <el-option v-for="item in charsetList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="text-align: right; margin: 0">
          <el-button type="primary" size="mini" @click="submit">确定</el-button>
        </div>
        <el-button type="primary" slot="reference">确定</el-button>
      </el-popover>
    </div>
  </el-drawer>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  data() {
    return {
      drawerVisible: false,
      loading: false,
      catalogList: [],
      dataList: [],
      selectedList: [],
      keyword: '',
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      selected: [],
      breadLeft: 0,
      config: {},
      popShow: false,
      fileType: 1,
      fileCharset: 'GBK',
      charsetList: ['Big5', 'GB18030', 'GBK', 'US-ASCII', 'UTF-16', 'UTF-8', 'x-mswin-936']
    }
  },
  computed: {
    showList() {
      if (!this.selected.length) return cloneDeep(this.catalogList)
      else {
        return this.selected[this.selected.length - 1]._children
      }
    }
  },
  methods: {
    showDrawer(config) {
      this.config = config
      this.getCatalogList()
      this.getSelectedList()
      this.drawerVisible = true
      this.$nextTick(() => (this.showTags = true))
    },
    unselected(item) {
      return !this.selectedList.find(tag => tag.tagId === item.tagId)
    },
    getBreadStyle() {
      // 面包屑样式
      this.$nextTick(() => {
        let totalWidth = 0
        let breadLeft = 0
        const bread = this.$refs.factoryBread
        if (bread) {
          let breadWidth = bread.$el.clientWidth
          for (let i = 0; i < bread.$children.length; i++) {
            totalWidth += bread.$children[i].$el.clientWidth
          }
          if (totalWidth > breadWidth) breadLeft = -(totalWidth - breadWidth + 20)
        }
        this.breadLeft = breadLeft
      })
    },
    getCatalogList() {
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/DclAssetCatalogDownList'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data && data.data.length) {
            var catalogs = this.$utils.arrayToTree(data.data.slice(1), {
              id: 'catalogId',
              pid: 'parentCatalogId',
              mainSort: 'catalogLevel'
            })
            this.catalogList = catalogs
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getSelectedList() {
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/beforSelectPage'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.selectedList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handleClickCatalog(item) {
      if (item.tail) {
        let result = Object.assign({}, item, { _children: [] })
        this.selected.push(result)
        this.getResults(item)
      } else {
        if (!item._children || !item._children.length)
          item._children = this.findCatalog(cloneDeep(this.catalogList), item.catalogId)
        this.selected.push(item)
      }
      this.getBreadStyle()
    },
    handleCurrentChange(val) {
      this.params.currentPageNum = val
      this.getResults()
    },
    search() {
      if (!this.keyword.trim().length) {
        if (!this.selected.length || !this.selected[0].catalogId) this.selected = []
        else this.clearKeyword()
        return
      }
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.getResults()
    },
    getResults(item) {
      this.loading = true
      this.params.queryParams.tagNm = this.keyword
      if (item && item.catalogId) this.params.queryParams.catalogId = item.catalogId
      else if (this.selected.length)
        this.params.queryParams.catalogId = this.selected[this.selected.length - 1].catalogId
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/downloadPageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (this.selected.length) this.selected[this.selected.length - 1]._children = data.data.records
          else {
            this.selected.push({ _children: data.data.records })
          }
          this.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    beforeClose() {
      this.clearDrawer()
      this.drawerVisible = false
    },
    addSelect(item) {
      if (this.selectedList.find(tag => tag.tagId === item.tagId)) {
        this.$message.info('已添加该标签')
        return
      }
      this.selectedList.push(item)
    },
    removeSelect(item) {
      const index = this.selectedList.findIndex(tag => tag.tagId === item.tagId)
      if (index >= 0) this.selectedList.splice(index, 1)
    },
    submit() {
      if (!this.selectedList.length) {
        this.$message.error('请选择标签')
        return
      }
      let config = {
        derivedTagId: this.config.derivedTagId,
        derivedTagNm: this.config.derivedTagNm,
        derivedTag: this.config.derivedTag
      }
      if (this.config.groupId) config.groupId = this.config.groupId
      if (!this.loading) {
        this.loading = true
        this.$ajax({
          url: this.$ajax.setUrl('tagFactory/downloadDeriveTagResult'),
          method: 'post',
          data: this.$ajax.setData({
            fileType: this.fileType,
            charsetName: this.fileType === 2 ? 'GBK' : this.fileCharset,
            config: config,
            tags: this.selectedList
          })
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.resetDownload()
            this.beforeClose()
            this.drawerVisible = false
          } else {
            this.$message.error(data.data || data.msg)
          }
          this.loading = false
        })
      }
    },
    resetDownload() {
      this.popShow = false
      this.fileType = 1
      this.fileCharset = 'GBK'
    },
    prev() {
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.keyword = ''
      this.selected.splice(this.selected.length - 1, 1)
      this.getBreadStyle()
    },
    findCatalog(list, targetId) {
      var children = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].catalogId === targetId) {
          children = list[i]._children || []
          break
        } else {
          if (list[i]._children) {
            children = this.findCatalog(list[i]._children, targetId)
            if (children.length) break
          }
        }
      }
      return children
    },
    clearKeyword() {
      if (this.selected[this.selected.length - 1].catalogId) {
        if (this.selected[this.selected.length - 1].tail) {
          this.getResults(this.selected[this.selected.length - 1])
        } else {
          this.selected[this.selected.length - 1]._children = this.findCatalog(
            cloneDeep(this.catalogList),
            this.selected[this.selected.length - 1].catalogId
          )
        }
      } else this.selected.splice(this.selected.length - 1, 1)
    },
    changeTab(index) {
      if (index === this.selected.length - 1) return
      this.keyword = ''
      this.selected.splice(index + 1)
      this.getBreadStyle()
    },
    clearDrawer() {
      this.catalogList = []
      this.dataList = []
      this.selectedList = []
      this.keyword = ''
      this.totalSize = 0
      this.selected = []
      this.breadLeft = 0
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.showTags = false
      this.totalSize = 0
    }
  }
}
</script>

<style lang="scss">
@import './factory-tag-drawer.scss';
</style>
